package com.isyscore.os.core.sqlcore;

/**
 * @author : zhan9yn
 * @version : 1.0
 * @description : TODO
 * @date : 2021/11/15 10:33 上午
 */
public class TDBuilder implements Builder{

    private static final String CREATE_TABLE = "CREATE TABLE \"%s\" ( \n";

    private static final String COL_DEF = "\"%s\" %s,\n";

    private static final String INSERT_TABLE = "INSERT INTO \"%s\"(\n";

    private static final String VALUES = "VALUES(\n";

    private StringBuilder _sql1;

    private StringBuilder _sql2;

    /*********** create table **********************/
    @Override
    public TDBuilder createTable(String tableName) {
        this._sql1 = new StringBuilder();
        this._sql1.append(String.format(CREATE_TABLE, tableName));
        _sql2 = null;
        return this;
    }

    @Override
    public TDBuilder addCol(String colName, String colType, String comment) {
        this._sql1.append(String.format(COL_DEF, colName, colType));
        return this;
    }

    /******************* insert data **************/

    @Override
    public TDBuilder insert(String table){
        this._sql1 = new StringBuilder(String.format(INSERT_TABLE, table));
        this._sql2 = new StringBuilder(VALUES);
        return this;
    }

    /**
     * @param col
     * @param val  目前只支持数值类型和字符类型
     * @author zhangyn
     * @date 2021/6/7 10:30 上午
     * @return com.isyscore.bigdatagroup.udmp.data.sqlcore.SQLBuilder
     */
    @Override
    public TDBuilder addValue(String col, Object val){
        this._sql1.append("\"" + col + "\",");
        if (val instanceof String) {
            this._sql2.append("'" + val + "',");
        }else {
            this._sql2.append(val + ",");
        }
        return this;
    }

    @Override
    public String build(){
        if (this._sql1 != null) {
            int index = this._sql1.lastIndexOf(",");
            this._sql1.delete(index, index + 1);
            this._sql1.append("\n)");
        }
        if (this._sql2 != null) {
            int index = this._sql2.lastIndexOf(",");
            this._sql2.delete(index, index + 1);
            this._sql2.append("\n)");
        }
        if (_sql2 != null) {
            _sql1.append("\n").append(_sql2);
        }
        return _sql1.toString();
    }
}
